package util;

import java.sql.*;
import java.util.Properties;

/**
 * @author oldliu
 * @since 1.0
 */
public class DBUtil {
    private static String className ;//= "com.mysql.cj.jdbc.Driver";
    private static String url  ;//= "jdbc:mysql://localhost:3308/java82";
    private static String user  ;//= "root";
    private static String pass ;// = "root1234";

    static {
        try {
            Properties p=new Properties();
            p.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
            //System.out.println(p);
            className=p.getProperty("className");
            url=p.getProperty("url");
            user=p.getProperty("user");
            pass=p.getProperty("pass");

            Class.forName(className);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private DBUtil() {
    }
    //获得数据库连接
    public static Connection get() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, pass);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return connection;
    }
    //关闭资源
    public static void close(ResultSet rs, Statement st, Connection con) {
        close(rs);
        close(st);
        close(con);
    }

    public static void close(Connection con) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {

            }
        }
    }

    public static void close(Statement st) {
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {

            }
        }
    }

    public static void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {

            }
        }
    }

}
